﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Clinica_Frba
{
    public partial class ListaRoles : Form
    {
        public char accion;
        private string consulta;
        private Conexion sqlCon = Conexion.getInstance();

        public ListaRoles()
        {
            InitializeComponent();
        }

        private void ListaRoles_Load(object sender, EventArgs e)
        {
            SqlDataAdapter adapter;
            DataTable table = new DataTable();
            DataRow row;

            switch (accion)
            {
                case Rol.Edit:{
                        this.buttonRol.HeaderText = "Modificar";
                        this.buttonRol.Text = "Editar";
                        this.Text = "Modificar Rol";
                        break;
                    }

                case Rol.Baja:{
                        this.buttonRol.HeaderText = "Dar de baja";
                        this.buttonRol.Text = "Eliminar";
                        this.Text = "Eliminar Rol";
                        break;
                    }

                case Rol.Display:{
                        this.buttonRol.HeaderText = "Visualizar";
                        this.buttonRol.Text = "Ver";
                        this.Text = "Listar Roles";
                        break;
                    }
            }

            this.buttonRol.UseColumnTextForButtonValue = true;

            //Fill ComboBox de Funcionalidades
            adapter = sqlCon.execQueryGrid("SELECT id_Funcionalidad, Nombre FROM b_sharp.Funcionalidad;");
            adapter.Fill(table);
            //Insertar fila vacia
            row = table.NewRow();
            row[0] = -1;
            table.Rows.InsertAt(row, 0);

            funCombo.DataSource = table;
            funCombo.DisplayMember = "Nombre";
            funCombo.ValueMember = "id_Funcionalidad";
        }

        private void dGridRoles_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            SqlCommand command;
            Rol formRol;

            // Ignorar clicks que no se hagan sobre el boton
            if (e.RowIndex < 0 || e.ColumnIndex !=
                dGridRoles.Columns["buttonRol"].Index) return;

            //Obtener id del Rol
            Int32 rolID = (Int32)dGridRoles.CurrentRow.Cells[1].Value;

            if (accion == Rol.Baja)
            {   //Marcar rol como inhabilitado y eliminar los usuarios asignados al mismo
                command = new SqlCommand("UPDATE b_sharp.Rol SET Habilitado = 'N' WHERE id_Rol = @idRol; " + 
                                         "DELETE b_sharp.Rol_Usuario WHERE id_rol = @idRol;", sqlCon.openCon());
                command.Parameters.AddWithValue("@idRol", rolID);
                command.ExecuteNonQuery();

                //Eliminarlo de la lista
                dGridRoles.Rows.RemoveAt(e.RowIndex);
                MessageBox.Show("El rol fue removido correctamente");
            }
            else
            {   //Llamar al formulario de rol para mostrar informacion detallada
                formRol = new Rol();
                formRol.accion = this.accion;
                formRol.idRol = rolID;
                formRol.nom = (string)dGridRoles.CurrentRow.Cells[2].Value;
                formRol.ShowDialog();

                //Actualizar datos
                refreshGrid();
            }
        }

        private void refreshGrid()
        {   //Actualizar el grid haciendo una nueva busqueda de los datos
            DataTable table = new DataTable();
            SqlDataAdapter adapter = sqlCon.execQueryGrid(consulta);
            adapter.Fill(table);
            dGridRoles.DataSource = table;
        }

        private void buscar_Click(object sender, EventArgs e)
        {
            string qSelect, qFrom, qWhere;
            SqlDataAdapter adapter;
            DataTable table = new DataTable();

            qSelect = "SELECT rol.id_Rol, rol.Nombre ";
            qFrom = "FROM b_sharp.Rol as rol ";
            qWhere = "WHERE rol.Nombre like '%" + rolName.Text + "%' ";

            if ((int)funCombo.SelectedValue != -1)
            {
                qFrom += "JOIN b_sharp.Rol_Funcionalidad as rfun ON rol.id_Rol = rfun.id_Rol ";
                qWhere += "AND rfun.id_Funcionalidad = " + (int)funCombo.SelectedValue +" ";
            }

            if (accion == Rol.Baja)
                qWhere += "AND rol.Habilitado = 'S' ";

            consulta = qSelect + qFrom + qWhere + ";";

            adapter = sqlCon.execQueryGrid(consulta);
            adapter.Fill(table);
            dGridRoles.DataSource = table;
        }

        private void limpiar_Click(object sender, EventArgs e)
        {
            rolName.Clear();
            funCombo.SelectedItem = funCombo.Items[0];

            while(dGridRoles.Rows.Count > 0)
                dGridRoles.Rows.RemoveAt(0);
        }
    }
}
